<template>
  <el-dialog v-model="dialogVisible" :title="title" width="30%" @close="dialogClose" destroy-on-close>
    <my-form v-bind="formConfig" v-model="formData" ref="formRef" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="handleEditClicked">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import MyForm from '@/components/form/form.vue'
export default defineComponent({
  components: {
    MyForm
  },
  props: {
    formConfig: {
      type: Object,
      required: true
    }
  },
  emits: ['addConfirmed', 'editConfirmed'],
  setup(props, { emit }) {
    let title = ref('新增')
    const formItems = props.formConfig?.formItems ?? []
    const formOriginData: any = {}
    for (const item of formItems) {
      formOriginData[item.prop] = ''
    }
    let formData = ref(formOriginData)
    let dialogVisible = ref(false)
    const open = (params: any, type: string) => {
      dialogVisible.value = true
      if (type === 'edit') {
        title.value = '编辑'
        formData.value = params
      } else {
        title.value = '新增'
      }
    }
    const resetForm = () => {
      formData.value = {}
    }
    const cancel = () => {
      dialogVisible.value = false
      resetForm()
    }
    const dialogClose = () => {
      resetForm()
    }

    const formRef = ref()
    const handleEditClicked = () => {
      if (title.value === '编辑') {
        emit('addConfirmed', formData.value)
      } else {
        emit('editConfirmed', formData.value)
      }
      // const boolValid = formRef.value.validateForm()
      // console.log(boolValid)
      // if (boolValid) {
      //   // 发送网络请求
      // }
    }
    return {
      formData,
      formRef,
      open,
      cancel,
      title,
      dialogClose,
      dialogVisible,
      handleEditClicked
    }
  }
})
</script>

<style scoped></style>
